//
//  AddTagController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "AddTagController.h"

#import "FormattingUtilities.h"
#import "GSSCommunicator.h"
#import "GSSTags.h"

@interface AddTagController (Private)

- (void)store:(NSString *)aName;
- (void)save:(id)sender;
- (void)done:(id)sender;

@end

@implementation AddTagController

@synthesize delegate;
@synthesize tags;

@synthesize nameCtl;

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = LocalizedString(@"Add tag");
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(done:)];
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save:)];
	
    GSSCommunicator *communicator = [GSSCommunicator defaultCommunicator];
	self.tags = communicator.tags;
    if (self.tags.isStale)
        [communicator updateMetaOfObject:self.tags];
    loadingView.hidden = !self.tags.isEmpty;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)viewDidUnload {
	[nameCtl release];
	nameCtl = nil;
}

- (void)dealloc {
    [super dealloc];
	[tags release];
	[nameCtl release];
}


- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    [self.tags addObserver:self forKeyPath:@"meta" options:0 context:NULL];
    [self.tags addObserver:self forKeyPath:@"error" options:0 context:NULL];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
    [self.tags removeObserver:self forKeyPath:@"meta"];
    [self.tags removeObserver:self forKeyPath:@"error"];
}

- (void)store:(NSString *)aName {
	[self.delegate tagAdded:aName];	
}

- (void)save:(id)sender {
	NSString *nameStr = [[nameCtl text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	if ([nameStr length] == 0)
		nameStr = nil;
	[self store:nameStr];
	[self done:sender];
}

- (void)done:(id)sender {
	[self.nameCtl resignFirstResponder];
	[self.navigationController popViewControllerAnimated:YES];
}

//MARK: Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"cellTypeNameEdit";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		[cell addSubview:self.nameCtl];
    }
    
    return cell;
}

//MARK: -
//MARK: Controls and functions

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)anObject change:(NSDictionary *)change context:(void *)context {    
    if ([keyPath isEqualToString:@"meta"]) {
		[tagCtl reloadAllComponents];
		loadingView.hidden = YES;
    } else if ([keyPath isEqualToString:@"error"]) {
			UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:LocalizedString(@"Tag error")
																message:LocalizedString(@"{Tag communication error}")
															   delegate:nil
													  cancelButtonTitle:LocalizedString(@"OK")
													  otherButtonTitles:nil];
			[alertView show];
			[alertView release];
			return;        
    }
}

- (UITextField *)nameCtl {
	
	if (nameCtl == nil) {
		nameCtl = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 10.0, 290.0, 24.0)];
		nameCtl.borderStyle = UITextBorderStyleNone;
		nameCtl.adjustsFontSizeToFitWidth = YES;
		nameCtl.minimumFontSize = 9.0;
		nameCtl.textColor = [UIColor colorWithRed:0.32 green:0.4 blue:0.57 alpha:1];
		nameCtl.backgroundColor = [UIColor clearColor];
		nameCtl.autocorrectionType = UITextAutocorrectionTypeNo;
		nameCtl.keyboardType = UIKeyboardTypeDefault;
		nameCtl.returnKeyType = UIReturnKeyDone;
		nameCtl.clearButtonMode = UITextFieldViewModeWhileEditing;
		nameCtl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		nameCtl.delegate = self;
		nameCtl.placeholder = LocalizedString(@"Tag");
	}

	return nameCtl;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

//MARK: -
//MARK: UIPickerView delegate and dataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSArray *items = self.tags.children;
	if (row >= 0 && row < [items count])
		nameCtl.text = [items objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.tags.children count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self.tags.children objectAtIndex:row];
}

@end
